package com.ysfxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ysfxt.constant.RedisConst;
import com.ysfxt.jwt.JwtHelper;
import com.ysfxt.model.SysUser;
import com.ysfxt.mapper.SysUserMapper;
import com.ysfxt.result.Result;
import com.ysfxt.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysfxt.utils.MD5;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ysfxt
 * @since 2024-03-29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    
    @Resource
    private SysUserMapper sysUserMapper;
    
    @Resource
    private RedisTemplate redisTemplate;
    
    /**
     * 管理员登录
     * @param sysUser
     * @return
     */
    @Override
    public Result login(SysUser sysUser) {
        LambdaQueryWrapper<SysUser> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,sysUser.getUsername());
        wrapper.eq(SysUser::getPassword, MD5.encrypt(sysUser.getPassword()));
        SysUser one = sysUserMapper.selectOne(wrapper);
        if(one==null)
            return Result.fail("账号或密码错误");
        String token = JwtHelper.createToken(one.getId(), RedisConst.ADMIN_LOGIN_KEY_PREFIX);
        one.setPassword("");
        redisTemplate.opsForValue()
                .set(RedisConst.ADMIN_LOGIN_KEY_PREFIX+one.getId(),
                        one,
                        RedisConst.ADMINKEY_TIMEOUT,
                        TimeUnit.DAYS);
        Map<String,Object> map = new HashMap<>();
        map.put("user",one);
        map.put("token",token);
        return Result.ok(map);
    }
}
